package com.ib.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ib.common.HttpUtils;

import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends CustomHeartbeatHandler {
	
	private static final String url = "http://apigw.eagle.mzj.net/scale/task/heartbeat?scaleId=%s";

	private static final Logger LOG = LoggerFactory.getLogger(ServerHandler.class);

	public ServerHandler() {
		super("server");
	}

	@Override
	protected void handleData(ChannelHandlerContext channelHandlerContext, Object msg) {
		String acceptValue = (String) msg;
		LOG.info("The server accept data is {}", acceptValue);
		JSONObject heartbeatJson = JSON.parseObject(acceptValue);
		String responseMsg = HttpUtils.sendGet(String.format(url,heartbeatJson.get("machineId"))); //处理广告业务
		channelHandlerContext.writeAndFlush(responseMsg);
		LOG.info("The server send data is {}" , responseMsg);
	}

	@Override
	protected void handleReaderIdle(ChannelHandlerContext ctx) {
		super.handleReaderIdle(ctx);
		LOG.error("---client {} reader timeout, close it---", ctx.channel().remoteAddress().toString() );
		ctx.close();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		LOG.error( "{} exception {}" ,name,cause.toString());
	}
}
